<?php

namespace App\Http\Controllers\Admin;

use App\Services\Admin\AdminsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AdminsController extends AdminBaseController
{
    protected $adminsService;

    public function __construct(AdminsService $adminsService)
    {
        $this->adminsService = $adminsService;
    }

    public function list(Request $request): \Illuminate\Http\JsonResponse
    {
        $params = $request->all();
        $data = $this->adminsService->list($params);
        return $this->success($data);
    }

    public function view(int $id): \Illuminate\Http\JsonResponse
    {
        $data = $this->adminsService->view($id);
        return $this->success($data);
    }

    public function create(Request $request): \Illuminate\Http\JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|string|min:4|max:20',
            'name' => 'required|string|min:4|max:20',
            'password' => 'required|string|min:6|max:20',
            'status' => 'integer|in:0,1'
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), 422);
        }

        $id = $this->adminsService->create($request->all());
        return $this->success($id);
    }

    public function update(int $id, Request $request): \Illuminate\Http\JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'username' => 'string|min:4|max:20',
            'email' => 'email|max:50',
            'password' => 'string|min:6|max:20',
            'status' => 'integer|in:0,1'
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), 422);
        }

        $rows = $this->adminsService->update($id, $request->all());
        return $this->success($rows);
    }

    public function delete(int $id): \Illuminate\Http\JsonResponse
    {
        $rows = $this->adminsService->delete($id);
        return $this->success($rows);
    }

    /**
     * 更新管理员状态
     */
    public function updateStatus(int $id, Request $request): \Illuminate\Http\JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'status' => 'required|integer|in:0,10'
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), 422);
        }

        $rows = $this->adminsService->update($id, ['status' => $request->input('status')]);
        return $this->success($rows);
    }
}
